package com.etc.library.controller;

import com.etc.library.annotation.Auth;
import com.etc.library.pojo.Record;
import com.etc.library.pojo.User;
import com.etc.library.service.RecordService;
import com.etc.library.util.ResultBody;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/record")
public class RecordController {

    @Autowired
    private RecordService recordService;

    @Auth
    @PostMapping("/add")
    public ResultBody add(@RequestBody Record record, HttpServletRequest request){
        Integer userId = Integer.valueOf(request.getAttribute("userId").toString());
        record.setStartTime(new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis()));
        record.setUserId(userId);
        if(recordService.add(record)){
            return ResultBody.success();
        }
        return  ResultBody.error();
    }

    @Auth
    @GetMapping("/list")
    public ResultBody list(@RequestParam Map<String,Object> params,HttpServletRequest request){
        int pageNum = 1;
        int pageSize = 999;
        try {
            pageNum = Integer.parseInt(params.get("pageNum").toString());
            pageSize = Integer.parseInt(params.get("pageSize").toString());
        }catch (Exception e){

        }
        PageHelper.startPage(pageNum,pageSize);

        Integer userId = null;
        if (Integer.parseInt(request.getAttribute("role").toString())==1){
            userId = Integer.valueOf(request.getAttribute("userId").toString());
        }
        params.put("userId", userId);

        List<Map<String, Object>> list = recordService.list(params);

        PageInfo info = new PageInfo(list);

        return ResultBody.success(info);
    }

    @PutMapping("/update")
    public ResultBody revert(@RequestBody Record record){
        record.setRealTime(new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis()));
        record.setRState(1);
        if (recordService.revert(record)){
            return ResultBody.success();
        }
        return ResultBody.error();
    }

}
